package hhm.android.main

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import hhm.android.library.LogUtils
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.BottomShareFriendsSheet
import siau.android.base.SBApplication
import siau.android.base.SBBaseActivity
import siau.android.base.WEBVIEW_ROUTER
import siau.android.http.model.FlutterUrlModel
import siau.android.library.KeyString
import wendu.dsbridge.CompletionHandler
import wendu.dsbridge.DWebView
import kotlin.properties.Delegates

@Route(path = WEBVIEW_ROUTER)
class WebViewActivity : SBBaseActivity() {

    private var hasX = false
    private lateinit var ll: LinearLayout
    private var share by Delegates.notNull<Boolean>()
    private lateinit var model: FlutterUrlModel
    private lateinit var xView: ImageView
    private lateinit var mWebView: DWebView

    private fun initX() {
        xView = ImageView(this)
        xView.setPadding(dp2px(12f), dp2px(12f), dp2px(12f), dp2px(12f))
        xView.setImageResource(R.mipmap.x)
        xView.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                finish()
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_webview)

        val url: String

        //获得控件
        mWebView = findViewById<View>(R.id.activity_webview_webview) as DWebView

        findViewById<FrameLayout>(siau.android.base.R.id.top_back).setOnClickListener {
            if (mWebView.canGoBack()) {
                mWebView.goBack()
            } else {
                finish()
            }
        }
        findViewById<View>(siau.android.base.R.id.title_bar_line).visibility = View.VISIBLE
        ll = findViewById(R.id.title_bar_right_ll)

        share = intent.getBooleanExtra(KeyString.share, false)
        if (share) {
            model = intent.getSerializableExtra(KeyString.data) as FlutterUrlModel
            url = model.activeUrl

            val shareView = ImageView(this)
            shareView.setPadding(dp2px(12f), dp2px(12f), dp2px(12f), dp2px(12f))
            shareView.setImageResource(R.mipmap.share)
            shareView.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    shareToFriends()
                }
            })
            ll.addView(shareView)
            val params = shareView.layoutParams
            params.width = dp2px(44f)
            params.height = dp2px(44f)
            shareView.layoutParams = params

            findViewById<TextView>(siau.android.base.R.id.top_title).text = model.activeName
        } else {
            url = intent.getStringExtra(KeyString.url)!!
        }

        //访问网页
        showLoadingFragment(R.id.activity_webview_fl)
        mWebView.loadUrl(url)
        initX()

        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        mWebView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                return if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("ftp")) {
                    view.loadUrl(url)
                    checkTitleGoBackX()
                    true
                } else {
                    try {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(intent)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    checkTitleGoBackX()
                    true
                }
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                removeLoadingFragment()
                super.onPageFinished(view, url)
            }
        }
        mWebView.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                if (!share) {
                    title?.let { findViewById<TextView>(siau.android.base.R.id.top_title).text = title }
                }
            }
        }

        mWebView.addJavascriptObject(JsEchoApi(), null)
    }

    private fun checkTitleGoBackX() {
        if (mWebView.canGoBack()) {
            if (!hasX) {
                hasX = true
                ll.addView(xView)
                val params = xView.layoutParams
                params.width = dp2px(44f)
                params.height = dp2px(44f)
                xView.layoutParams = params
            }
        } else {
            if (hasX) {
                hasX = false
                ll.removeView(xView)
            }
        }
    }

    private fun shareToFriends() {
        val bsfs = BottomShareFriendsSheet(this) {
            if (it == 0) {

                //初始化一个WXWebpageObject填写url
                val webpageObject = WXWebpageObject()
                webpageObject.webpageUrl = model.shareUrl
                //用WXWebpageObject对象初始化一个WXMediaMessage
                val msg = WXMediaMessage(webpageObject)
                msg.title = model.activeName
                msg.description = SBApplication.userData.nickName + "邀你参加活动"

                Glide.with(this).asBitmap().load(model.activeImg).into(object : SimpleTarget<Bitmap>(200, 200) {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        msg.setThumbImage(resource)

                        val req = SendMessageToWX.Req()
                        req.transaction = System.currentTimeMillis().toString()
                        req.message = msg
                        req.scene = SendMessageToWX.Req.WXSceneTimeline
//                        req.scene = SendMessageToWX.Req.WXSceneSession
                        SBApplication.api.sendReq(req)
                    }
                })

            } else if (it == 1) {

                //初始化一个WXWebpageObject填写url
                val webpageObject = WXWebpageObject()
                webpageObject.webpageUrl = model.shareUrl
                //用WXWebpageObject对象初始化一个WXMediaMessage
                val msg = WXMediaMessage(webpageObject)
                msg.title = model.activeName
                msg.description = SBApplication.userData.nickName + "邀你参加活动"

                Glide.with(this).asBitmap().load(model.activeImg).into(object : SimpleTarget<Bitmap>(200, 200) {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        msg.setThumbImage(resource)

                        val req = SendMessageToWX.Req()
                        req.transaction = System.currentTimeMillis().toString()
                        req.message = msg
//                req.scene =  SendMessageToWX.Req.WXSceneTimeline
                        req.scene = SendMessageToWX.Req.WXSceneSession
                        SBApplication.api.sendReq(req)
                    }
                })

            }
        }
        bsfs.show()
    }

    class JsEchoApi {
        /**
         * 同步方法
         */
        @JavascriptInterface
        fun logoutSyn(args: Any): Any {
            LogUtils.d("hhm", "aaaaaaaaaaaaaa")

            SBApplication.sendOnePointReceiver(false)

            return args
        }

//        /**
//         * 异步方法
//         */
//        @JavascriptInterface
//        fun logoutSyn(args: Any?, handler: CompletionHandler<Any>) {
//            LogUtils.d("hhm", "bbbbbbbbbbbbbbb")
//
//            SBApplication.sendOnePointReceiver()
//
//            handler.complete(args)
//        }

        /**
         * 同步方法
         */
        @JavascriptInterface
        fun getTokenSyn(args: Any): Any {
            LogUtils.d("hhm", "cccccccccccccccc")

            return "Bearer " + KeyString.token
        }

//        /**
//         * 异步方法
//         */
//        @JavascriptInterface
//        fun getTokenSyn(args: Any?, handler: CompletionHandler<Any>) {
//            LogUtils.d("hhm", "dddddddddddddddd")
//
//            handler.complete("Bearer " + KeyString.token)
//        }
    }
}